const fs = require('fs');
const sqlite3 = require('sqlite3').verbose();

class SqliteDb {
  constructor(file) {

    if (!fs.existsSync(file)) {
      console.log('Creating db file!');
      fs.openSync(file, 'w');
    }
    this.db = new sqlite3.Database(file);
  }

  error(err) {
    console.log("Error Message:", err.message, "ErrorNumber:", err.no);
  }

  createTable(sql) {
    let that = this;
    this.db.serialize(function () {
      this.run(sql, function (err) {
        if (null != err) {
          that.error(err);
          return;
        }
      });
    });
  };

  insertData(sql, objects) {
    let that = this;
    this.db.serialize(function () {
      let stmt = that.db.prepare(sql);
      for (let i = 0; i < objects.length; i++) {
        stmt.run(objects[i]);
      }
      stmt.finalize();
    });
  };

  queryData(sql, callback) {
    let that = this;
    this.db.all(sql, function (err, rows) {
      if (null != err) {
        that.error(err);
        return;
      }
      if (callback) {
        callback(rows);
      }
    });
  };

  executeSql(sql) {
    let that = this;
    this.db.run(sql, function (err) {
      if (null != err) {
        that.error(err);
      }
    });
  };

  close() {
    this.db.close();
  };
}

exports.SqliteDb = SqliteDb;